#![cfg_attr(
  all(not(debug_assertions), target_os = "windows"),
  windows_subsystem = "windows"
)]

use tauri::{window::WindowBuilder, WindowUrl};

fn main() {
  tauri::Builder::default()
    .setup(|app| {
      #[allow(unused_mut)]
      let mut window_builder = WindowBuilder::new(app, "app", WindowUrl::default())
        .title("amc")
        .inner_size(1000., 800.)
        .min_inner_size(600., 400.);

      #[cfg(target_os = "windows")]
      {
        window_builder = window_builder.transparent(true);
        window_builder = window_builder.decorations(false);
      }

      let window = window_builder.build().unwrap();

      #[cfg(target_os = "windows")]
      {
        let _ = window_shadows::set_shadow(&window, true);
        let _ = window_vibrancy::apply_blur(&window, Some((0, 0, 0, 0)));
      }

      #[cfg(debug_assertions)]
      window.open_devtools();

      std::thread::spawn(|| {
        let server = match tiny_http::Server::http("localhost:3000") {
          Ok(s) => s,
          Err(e) => {
            eprintln!("{}", e);
            std::process::exit(1);
          }
        };
        loop {
          if let Ok(mut request) = server.recv() {
            let mut body = Vec::new();
            let _ = request.as_reader().read_to_end(&mut body);
            let response = tiny_http::Response::new(
              tiny_http::StatusCode(200),
              request.headers().to_vec(),
              std::io::Cursor::new(body),
              request.body_length(),
              None,
            );
            let _ = request.respond(response);
          }
        }
      });

      Ok(())
    })
    .on_page_load(|window, _| {
      window.listen("tauri://update-available".to_string(), move |msg| {
        println!("Tauri New version available: {:?}", msg);
      });
      window.listen("tauri://update-status".to_string(), move |msg| {
        println!("Tauri Update status: {:?}", msg);
      });
    })
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}
